﻿using System;
using System.ComponentModel;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using YArchitech.Controls;
using YArchitech.LIB;
using Hongye.ProductLicense;
using Microsoft.Win32;

namespace YArchitech.Public.Encrypt
{
	internal class TrialLicenseChecker : LicenseChecker
	{
		public TrialLicenseChecker()
		{
			this.m_LicenseValid = false;
			this._isPrivateVersion = false;
		}

		public override bool GetLicense()
		{
			string setting = IniHelper.GetSetting("Product", "AreYouSureContinueUse", Product.DefaultConfigFile, "");
			this._isPrivateVersion = (setting == "Yes");
			if (this._isPrivateVersion)
			{
				this.m_LicenseValid = true;
				return true;
			}
			this.m_LicenseValid = this.GetLicense_ByEncrypt();
			return this.m_LicenseValid;
		}

		public override bool CheckLicense()
		{
			if (this._isPrivateVersion)
			{
				this.m_LicenseValid = true;
				return true;
			}
			if (!this.m_LicenseValid)
			{
				Product.SaveSoftWareType(3);
				base.OnLicenseError();
			}
			return this.m_LicenseValid;
		}

		public override void ReleaseLicense()
		{
		}

		private bool GetLicense_ByTime()
		{
			DateTime dateTime = new DateTime(2015, 9, 30);
			try
			{
				dateTime = Convert.ToDateTime(HYStringEncryptUtility.Decrypt(IniHelper.GetSetting("Product", "LimitTime", Product.DefaultConfigFile, "9E9534F9289C6D37CA810D8E43931D141C28B5D9BA07498D")));
			}
			catch
			{
				dateTime = new DateTime(2015, 9, 30);
			}
			Product.SaveTrialExpirationType(1);
			if (DateTime.Now < dateTime)
			{
				this.m_LicenseValid = true;
				int days = (dateTime - DateTime.Now).Days;
				Product.SaveTrialExecutionDays(days);
				if (days < 6)
				{
					this._hasTiped = true;
					MessageBox.Show(string.Format("试用即将到期，剩余天数为{0}天", days));
				}
				this.m_ErrorMessage = string.Empty;
			}
			else
			{
				Product.SaveTrialExecutionDays(0);
				this.m_ErrorMessage = "试用已过期，请选择正式版启动!";
				this.m_LicenseValid = false;
				Product.SaveSoftWareType(3);
			}
			return this.m_LicenseValid;
		}

		private bool GetLicense_NewTimeRuler()
		{
			this.CreatNewFile();
			DateTime installNewTime = this.GetInstallNewTime();
			DateTime lastTime = this.GetLastTime();
			DateTime expiredTime = installNewTime.AddMonths(6);
			DateTime now = DateTime.Now;
			if (!this.CheckTime(installNewTime, lastTime))
			{
				return false;
			}
			this.SaveLastRunTime(now);
			this._remainingDays = this.GetRemainingDays(now, expiredTime);
			if (!this._hasTiped && this._remainingDays < 6)
			{
				this._hasTiped = true;
				YJKMessageBox.Information(string.Format("试用即将到期，剩余天数为{0}天", this._remainingDays + 1));
			}
			TrialLicenseChecker._checkWorker = new BackgroundWorker();
			TrialLicenseChecker._checkWorker.DoWork += this.CheckTrialTime;
			TrialLicenseChecker._checkWorker.RunWorkerAsync();
			return true;
		}

		private bool TimeCompare(DateTime time1, DateTime time2)
		{
			return time1 > time2;
		}

		private bool GetLicense_NewRuler()
		{
			this.CreateFile();
			this.GetTimes();
			this.SaveLastTime(DateTime.Now);
			if (!this.CheckTime())
			{
				return false;
			}
			if (!this._hasTiped && this._remainingDays < 6)
			{
				this._hasTiped = true;
				MessageBox.Show(string.Format("试用即将到期，剩余天数为{0}天", this._remainingDays + 1));
			}
			TrialLicenseChecker._checkWorker = new BackgroundWorker();
			TrialLicenseChecker._checkWorker.DoWork += this.TestTrialTime;
			TrialLicenseChecker._checkWorker.RunWorkerAsync();
			return true;
		}

		private void CheckTrialTime(object sender, DoWorkEventArgs e)
		{
			for (;;)
			{
				DateTime installNewTime = this.GetInstallNewTime();
				DateTime lastTime = this.GetLastTime();
				installNewTime.AddMonths(6);
				DateTime now = DateTime.Now;
				Thread.Sleep(3600000);
				if (this.CheckTime(installNewTime, lastTime))
				{
					this.SaveLastRunTime(DateTime.Now);
				}
			}
		}

		private void TestTrialTime(object sender, DoWorkEventArgs e)
		{
			int num = IniHelper.GetIntSetting(this._section, "ElapsedSpeed", this._filename, 1);
			if (num <= 0 || num > 3600)
			{
				num = 1;
			}
			for (;;)
			{
				int elapsedMinues = this.GetElapsedMinues();
				this._elapsedMinutes = elapsedMinues + 60;
				this.SaveLastTime(DateTime.Now);
				Thread.Sleep(3600000 / num);
				if (!this.CheckTime())
				{
				}
			}
		}

		private bool CheckTime(DateTime installTime, DateTime lastTime)
		{
			this.m_LicenseValid = true;
			DateTime time = installTime.AddMonths(6);
			DateTime now = DateTime.Now;
			if (this.TimeCompare(installTime, now) || this.TimeCompare(lastTime, now) || this.TimeCompare(now, time))
			{
				this.m_ErrorMessage = "试用已过期，请选择正式版启动!";
				Product.SaveSoftWareType(3);
				this.m_LicenseValid = false;
			}
			return this.m_LicenseValid;
		}

		private bool CheckTime()
		{
			this.m_LicenseValid = true;
			if (this._elapsedMinutes >= 129600)
			{
				this.m_ErrorMessage = "试用已过期，请选择正式版启动!";
				Product.SaveSoftWareType(3);
				this.m_LicenseValid = false;
			}
			return this.m_LicenseValid;
		}

		private void SaveLastTime(DateTime dt)
		{
			try
			{
				string value = this.DateTimeToString(dt);
				IniHelper.WriteSetting(this._section, "LastTime", value, this._filename);
				this.SetRegValue("LastTime", value);
				IniHelper.WriteSetting(this._section, "ElapsedMinutes", this._elapsedMinutes, this._filename);
				this.SetRegValue("ElapsedMinutes", this._elapsedMinutes);
			}
			catch (Exception)
			{
			}
		}

		private void GetTimes()
		{
			this.GetInstallTime();
			this._elapsedMinutes = this.GetElapsedMinues();
			this._remainingDays = this.GetRemainingDays();
		}

		private DateTime GetLastTime()
		{
			DateTime result = new DateTime(2017, 11, 30);
			try
			{
				string regValue = this.GetRegValue("LastTime", this.DateTimeToString(DateTime.Now));
				DateTime time = this.StringToDateTime(regValue);
				string setting = IniHelper.GetSetting(this._section, "LastTime", this.fileName, this.DateTimeToString(DateTime.Now));
				DateTime time2 = this.StringToDateTime(setting);
				result = this.Max(time, time2);
			}
			catch (Exception ex)
			{
				string message = ex.Message;
				result = new DateTime(2017, 11, 31);
			}
			return result;
		}

		private void SaveLastRunTime(DateTime lastTime)
		{
			try
			{
				string value = this.DateTimeToString(lastTime);
				IniHelper.WriteSetting(this._section, "LastTime", value, this.fileName);
				this.SetRegValue("LastTime", value);
			}
			catch (Exception ex)
			{
				string message = ex.Message;
			}
		}

		private DateTime GetInstallTime()
		{
			DateTime result;
			try
			{
				string regValue = this.GetRegValue("InstallTime", this.DateTimeToString(DateTime.Now));
				DateTime t = this.StringToDateTime(regValue);
				string setting = IniHelper.GetSetting(this._section, "InstallTime", this._filename, this.DateTimeToString(DateTime.Now));
				DateTime t2 = this.StringToDateTime(setting);
				DateTime dateTime = this.Min(t, t2);
				IniHelper.WriteSetting(this._section, "Version", Product.GetSoftWareVer(), this._filename);
				IniHelper.WriteSetting(this._section, "InstallTime", this.DateTimeToString(dateTime), this._filename);
				this.SetRegValue("InstallTime", this.DateTimeToString(dateTime));
				result = dateTime;
			}
			catch
			{
				result = new DateTime(2016, 4, 21);
			}
			return result;
		}

		private int GetElapsedMinues()
		{
			int intSetting = IniHelper.GetIntSetting(this._section, "ElapsedMinutes", this._filename, 0);
			int result;
			try
			{
				int regValue = this.GetRegValue("ElapsedMinutes", 0);
				result = Math.Max(intSetting, regValue);
			}
			catch
			{
				result = intSetting;
			}
			return result;
		}

		private int GetRemainingDays()
		{
			int num = (129600 - this._elapsedMinutes) / 720;
			object obj = (num <= 0) ? 0 : num;
			Product.SaveTrialExpirationType(1);
			object obj2 = obj;
			Product.SaveTrialExecutionDays(obj2);
			return obj2;
		}

		private int GetRemainingDays(DateTime currentTime, DateTime expiredTime)
		{
			int days = expiredTime.Subtract(currentTime).Days;
			Product.SaveTrialExpirationType(1);
			Product.SaveTrialExecutionDays(days);
			return days;
		}

		private bool IsFileExists
		{
			get
			{
				return File.Exists(this._filename);
			}
		}

		private void CreateFile()
		{
			try
			{
				IniHelper.WriteSetting(this._section, "LastStart", this.DateTimeToString(DateTime.Now), this._filename);
				FileAttributes attributes = File.GetAttributes(this._filename);
				File.SetAttributes(this._filename, attributes | FileAttributes.Hidden);
			}
			catch
			{
				this._elapsedMinutes = 0;
			}
		}

		private void CreatNewFile()
		{
			try
			{
				IniHelper.WriteSetting(this._section, "LastStart", this.DateTimeToString(DateTime.Now), this.fileName);
				FileAttributes attributes = File.GetAttributes(this.fileName);
				File.SetAttributes(this.fileName, attributes | FileAttributes.Hidden);
			}
			catch
			{
			}
		}

		private string DateTimeToString(DateTime dt)
		{
			return dt.ToString("yyyy-MM-dd HH:mm:ss");
		}

		private DateTime StringToDateTime(string str)
		{
			DateTime result;
			try
			{
				result = DateTime.Parse(str);
			}
			catch
			{
				result = DateTime.Now;
			}
			return result;
		}

		private DateTime Min(DateTime t1, DateTime t2)
		{
			if (!(t1 < t2))
			{
				return t2;
			}
			return t1;
		}

		private DateTime Max(DateTime time1, DateTime time2)
		{
			if (!(time1 > time2))
			{
				return time2;
			}
			return time1;
		}

		private bool CompareTime(DateTime installTime, DateTime currentTime)
		{
			return currentTime < installTime;
		}

		private string GetRegValue(string section, string defValue)
		{
			string result;
			try
			{
				RegistryKey registryKey = Registry.CurrentUser.CreateSubKey(this._regkeyPath);
				string text = (string)registryKey.GetValue(section, defValue);
				registryKey.Close();
				result = text;
			}
			catch
			{
				result = defValue;
			}
			return result;
		}

		private int GetRegValue(string section, int defValue)
		{
			int result;
			try
			{
				RegistryKey registryKey = Registry.CurrentUser.CreateSubKey(this._regkeyPath);
				int num = (int)registryKey.GetValue(section, defValue);
				registryKey.Close();
				result = num;
			}
			catch
			{
				result = defValue;
			}
			return result;
		}

		private void SetRegValue(string section, string Value)
		{
			try
			{
				RegistryKey registryKey = Registry.CurrentUser.CreateSubKey(this._regkeyPath);
				registryKey.SetValue(section, Value);
				registryKey.Close();
			}
			catch
			{
			}
		}

		private void SetRegValue(string section, int defValue)
		{
			try
			{
				RegistryKey registryKey = Registry.CurrentUser.CreateSubKey(this._regkeyPath);
				registryKey.SetValue(section, defValue);
				registryKey.Close();
			}
			catch
			{
			}
		}

		private bool GetLicenseByEncryptNew()
		{
			this.professionalLicenseCode = this.GetLicenseCode();
			this.professionalLicense = new TrialLicense((int)base.ProductId);
			this.professionalLicense.ProductName = base.ProductName;
			this.professionalLicense.ProductVersion = Product.GetSoftWareVer();
			this.professionalLicense.LicenseCode = this.professionalLicenseCode;
			this.professionalLicense.UpdateLicense();
			this.m_LicenseValid = this.professionalLicense.GetLicense();
			if (!this.m_LicenseValid && !this.m_LicenseValid)
			{
				if (!this.ConfigLicense(this.professionalLicense, false))
				{
					this.m_ErrorMessage = "注册失败!\n失败代码是" + this.professionalLicense.ErrorCode.ToString();
					return false;
				}
				this.GetLicenseByEncryptNew();
			}
			LicenseStatus licenseStatus = default(LicenseStatus);
			this.professionalLicense.GetLicenseStatus(ref licenseStatus);
			DateTime now = DateTime.Now;
			DateTime lkdt = licenseStatus.LKDT;
			TimeSpan timeSpan = lkdt - now;
			if (licenseStatus.HasExpirationDateLimit)
			{
				if (timeSpan.TotalMinutes > 0.0)
				{
					this.m_ErrorMessage = string.Format("计算机时间错误！\n\n您最后一次使用软件的时间为{0}\n当前时间为{1}\n\n请修正计算机时间或重新注册！", lkdt.ToString(), now.ToString());
					this.m_LicenseValid = false;
					return false;
				}
				int days = (licenseStatus.ExpirationDate - now).Days;
				Product.SaveTrialExpirationType(1);
				Product.SaveTrialExecutionDays(days);
				if (days < 6)
				{
					this.m_ErrorMessage = string.Format("试用即将到期，剩余天数 {0} 天。", days);
					MessageBox.Show(this.m_ErrorMessage);
				}
			}
			return this.m_LicenseValid;
		}

		private bool GetLicense_ByEncrypt()
		{
			this.m_LicenseCode = this.GetLicenseCode();
			this.m_License = new TrialLicense((int)base.ProductId);
			this.m_License.ProductName = base.ProductName;
			this.m_License.ProductVersion = Product.GetSoftWareVer();
			this.m_License.LicenseCode = this.m_LicenseCode;
			this.m_License.UpdateLicense();
			this.m_LicenseValid = this.m_License.GetLicense();
			if (!this.m_LicenseValid)
			{
				if (!this.ConfigLicense())
				{
					this.m_ErrorMessage = "注册失败!\n失败代码是" + this.m_License.ErrorCode.ToString();
					return false;
				}
				this.GetLicense_ByEncrypt();
			}
			LicenseStatus licenseStatus = default(LicenseStatus);
			this.m_License.GetLicenseStatus(ref licenseStatus);
			DateTime now = DateTime.Now;
			DateTime lkdt = licenseStatus.LKDT;
			TimeSpan timeSpan = lkdt - now;
			if (licenseStatus.HasExpirationDateLimit)
			{
				if (timeSpan.TotalMinutes > 0.0)
				{
					this.m_ErrorMessage = string.Format("计算机时间错误！\n\n您最后一次使用软件的时间为{0}\n当前时间为{1}\n\n请修正计算机时间或重新注册！", lkdt.ToString(), now.ToString());
					this.m_LicenseValid = false;
					return false;
				}
				Product.SaveTrialExpirationType(1);
				int days = (licenseStatus.ExpirationDate - now).Days;
				Product.SaveTrialExecutionDays(days);
				if (days < 6)
				{
					this.m_ErrorMessage = string.Format("试用即将到期，剩余天数 {0} 天。", days);
					MessageBox.Show(this.m_ErrorMessage);
				}
			}
			int executionCounter = licenseStatus.ExecutionCounter;
			if (licenseStatus.HasExecutionLimit)
			{
				Product.SaveTrialExpirationType(0);
				Product.SaveTrialExecutionCounter(executionCounter);
				if (executionCounter < 6)
				{
					this.m_ErrorMessage = string.Format("试用即将到期，剩余次数 {0} 次。", licenseStatus.ExecutionCounter);
					MessageBox.Show(this.m_ErrorMessage);
				}
				else
				{
					this.m_ErrorMessage = string.Empty;
				}
			}
			return this.m_LicenseValid;
		}

		private bool GetLicense_NewTimeLongHuRuler()
		{
			this.m_LicenseCode = this.GetLicenseCode();
			this.m_License = new TrialLicense((int)base.ProductId);
			if (string.IsNullOrEmpty(this.m_LicenseCode))
			{
				if (!this.m_License.ConfigLicense())
				{
					this.m_ErrorMessage = "注册失败!\n失败代码是" + this.m_License.ErrorCode.ToString();
					return false;
				}
				this.m_LicenseCode = this.GetLicenseCode();
			}
			LicenseCodeInfo licenseCodeInfo = default(LicenseCodeInfo);
			this.m_License.GetLicenseCodeInfo(this.m_LicenseCode, ref licenseCodeInfo);
			int trialDays = licenseCodeInfo.TrialDays;
			DateTime expireDateTime = this.GetExpireDateTime(this.m_LicenseCode, trialDays);
			DateTime now = DateTime.Now;
			if (trialDays > 0)
			{
				if (now > expireDateTime)
				{
					if (!this.m_License.ConfigLicense())
					{
						this.m_ErrorMessage = "注册失败!\n失败代码是" + this.m_License.ErrorCode.ToString();
						return false;
					}
					this.GetLicense_NewTimeLongHuRuler();
				}
				this.m_LicenseValid = true;
				int days = expireDateTime.Subtract(now).Days;
				if (days < 6)
				{
					this.m_ErrorMessage = string.Format("试用即将到期，剩余天数 {0} 天。", days + 1);
					YJKMessageBox.Information(this.m_ErrorMessage);
				}
				else
				{
					this.m_ErrorMessage = string.Empty;
				}
			}
			return this.m_LicenseValid;
		}

		private DateTime GetExpireDateTime(string licenseCode, int trialDays)
		{
			DateTime dateTime = new DateTime(2000, 1, 1);
			string text = Environment.ExpandEnvironmentVariables("%appdata%\\Hongye\\Product Licenses\\F000" + base.ProductId + ".ini");
			string setting = IniHelper.GetSetting(this._section, text, this.fileName, "");
			if (string.IsNullOrEmpty(setting))
			{
				dateTime = DateTime.Now.AddDays((double)trialDays);
				IniHelper.WriteSetting(this._section, licenseCode, this.DateTimeToString(dateTime), text);
			}
			else
			{
				dateTime = this.StringToDateTime(setting);
			}
			return dateTime;
		}

		private DateTime GetInstallNewTime()
		{
			DateTime dateTime = new DateTime(2017, 5, 31);
			try
			{
				string regValue = this.GetRegValue("InstallTime", this.DateTimeToString(DateTime.Now));
				DateTime t = this.StringToDateTime(regValue);
				string setting = IniHelper.GetSetting(this._section, "InstallTime", this.fileName, this.DateTimeToString(DateTime.Now));
				DateTime t2 = this.StringToDateTime(setting);
				dateTime = this.Min(t, t2);
				IniHelper.WriteSetting(this._section, "Version", Product.GetSoftWareVer(), this.fileName);
				string value = this.DateTimeToString(dateTime);
				IniHelper.WriteSetting(this._section, "InstallTime", value, this.fileName);
				this.SetRegValue("InstallTime", value);
			}
			catch (Exception ex)
			{
				dateTime = new DateTime(2017, 5, 31);
				string message = ex.Message;
			}
			return dateTime;
		}

		private bool ConfigLicense()
		{
			this.m_LicenseValid = false;
			if (this.m_License.ConfigLicense())
			{
				this.m_LicenseCode = this.m_License.LicenseCode;
				this.SaveLicenseCode(this.m_LicenseCode);
				return true;
			}
			return false;
		}

		private bool ConfigLicense(TrialLicense m_License, bool beBIMSpace = false)
		{
			this.m_LicenseValid = false;
			if (m_License.ConfigLicense())
			{
				this.m_LicenseCode = m_License.LicenseCode;
				if (!beBIMSpace)
				{
					this.SaveLicenseCode(this.m_LicenseCode);
				}
				else
				{
					this.SaveBIMSpaceLicenseCode(this.m_LicenseCode);
				}
				return true;
			}
			return false;
		}

		private static string ProductIdToFileNameStr(uint productId)
		{
			string text = productId.ToString("X4");
			string str = text.Substring(0, 2);
			return text.Substring(2, 2) + str + "0100";
		}

		private string LicenseCodeFilePath
		{
			get
			{
				if (string.IsNullOrEmpty(this.m_licenseCodeFile))
				{
					string path = Environment.ExpandEnvironmentVariables("%Appdata%\\YArchitech\\Product Licenses\\");
					string path2 = TrialLicenseChecker.ProductIdToFileNameStr(base.ProductId) + ".dat";
					this.m_licenseCodeFile = Path.Combine(path, path2);
				}
				return this.m_licenseCodeFile;
			}
		}

		private string LicenseCodeBIMSpaceFilePath
		{
			get
			{
				if (string.IsNullOrEmpty(this.m_licenseBIMSpaceCodeFile))
				{
					string path = Environment.ExpandEnvironmentVariables("%Appdata%\\YArchitech\\Product Licenses\\");
					string path2 = TrialLicenseChecker.ProductIdToFileNameStr(52u) + ".dat";
					this.m_licenseBIMSpaceCodeFile = Path.Combine(path, path2);
				}
				return this.m_licenseBIMSpaceCodeFile;
			}
		}

		private void SaveBIMSpaceLicenseCode(string licenseCode)
		{
			StreamWriter streamWriter = new StreamWriter(this.LicenseCodeBIMSpaceFilePath);
			streamWriter.WriteLine(licenseCode);
			streamWriter.Close();
		}

		private void SaveLicenseCode(string licenseCode)
		{
			StreamWriter streamWriter = new StreamWriter(this.LicenseCodeFilePath);
			streamWriter.WriteLine(licenseCode);
			streamWriter.Close();
		}

		private string GetLicenseCode()
		{
			string licenseCodeFilePath = this.LicenseCodeFilePath;
			if (!File.Exists(licenseCodeFilePath))
			{
				return string.Empty;
			}
			StreamReader streamReader = new StreamReader(licenseCodeFilePath);
			string result = streamReader.ReadLine();
			streamReader.Close();
			return result;
		}

		private string GetBIMSpaceLicenseCode()
		{
			string licenseCodeBIMSpaceFilePath = this.LicenseCodeBIMSpaceFilePath;
			if (!File.Exists(licenseCodeBIMSpaceFilePath))
			{
				return string.Empty;
			}
			StreamReader streamReader = new StreamReader(licenseCodeBIMSpaceFilePath);
			string result = streamReader.ReadLine();
			streamReader.Close();
			return result;
		}

		private bool _isPrivateVersion;

		private static BackgroundWorker _checkWorker;

		private bool _hasTiped;

		private readonly string _filename = Environment.ExpandEnvironmentVariables("%appdata%\\Hongye\\Product Licenses\\F9030200.ini");

		private readonly string fileName = Environment.ExpandEnvironmentVariables("%appdata%\\Hongye\\Product Licenses\\F9030201.ini");

		private readonly string _regkeyPath = "Software\\YArchitech\\BIMSpace\\" + Product.GetSoftWareVer();

		private readonly string _section = "Trial" + Product.GetSoftWareVer();

		private const int MinutesPerDay = 720;

		private const int TotalMinutes = 129600;

		private const int IntervalMinutes = 60;

		private const int Intervalmilliseconds = 3600000;

		private int _elapsedMinutes = 129600;

		private int _remainingDays;

		private string professionalLicenseCode;

		private string bimSpaceLicenseCode;

		private TrialLicense professionalLicense;

		private TrialLicense bimSpaceLicense;

		private string m_LicenseCode;

		private TrialLicense m_License;

		private string m_licenseCodeFile = string.Empty;

		private string m_licenseBIMSpaceCodeFile = string.Empty;
	}
}
